package com.hxh.generater.springBoot.springboot3_vue3.gen;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.hxh.config.Constants;
import com.hxh.entity.Project;
import com.hxh.entity.ProjectDatasource;
import com.hxh.generater.springBoot.genBase.GenSystemBase;
import com.hxh.util.DirClone;
import com.hxh.util.GenUtil;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GenSb3Vue3SystemBase implements GenSystemBase {
    private static final String FILE_PATH_PRE = Constants.templatePathPrefix + "springboot3_vue3\\template\\";


    /**
     * @param project
     */
    @Override
    public void generationSystemBase(Project project) {
        ReplaceGroupIdUtil.replaceDirectory("common", project);

        ReplaceGroupIdUtil.replaceUtil("Application", null, "Application", project);
        ReplaceGroupIdUtil.replaceDirectory("model", project);
        ReplaceGroupIdUtil.replaceDirectory("plugin\\dupsubmit\\annotation", project);

        ReplaceGroupIdUtil.replaceUtil("plugin\\dupsubmit\\aspect\\DuplicateSubmitAspect", "plugin\\dupsubmit\\aspect\\", "DuplicateSubmitAspect", project);
        ReplaceGroupIdUtil.replaceDirectory("plugin\\mybatis", project);

        generationApplicationYml(project);
        generationApplicationDBYml(project);
        generationApplicationSecurityYml(project);
        generationApplicationServiceYml(project);
        generationApplicationSwaggerYml(project);
        generationPom(project);
        generationOther(project);
    }
    private void generationOther(Project project) {
        String sourcePath =FILE_PATH_PRE + "readme.md";
        String destPath = project.getBackendProject().getProjectDir() + project.getBackendProject().getProjectName() + "\\readme.md";
        DirClone.fileInputOutput(sourcePath, destPath);

        sourcePath =FILE_PATH_PRE + "LICENSE";
        destPath = project.getBackendProject().getProjectDir() + project.getBackendProject().getProjectName() + "\\LICENSE";
        DirClone.fileInputOutput(sourcePath, destPath);
    }

    /**
     * 生成application.yml
     *
     * @param project
     */
    private void generationApplicationYml(Project project) {
        try {
            // 使用 try-with-resources 保证资源自动关闭
            File classFile = GenUtil.newFile(project, "applicationConfig", "application");
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(classFile))) {

                File template = new File(FILE_PATH_PRE + "resources\\config\\application");
                try (BufferedReader br = new BufferedReader(new FileReader(template))) {
                    String line;
                    while ((line = br.readLine()) != null) {
                        if (StringUtils.isNotBlank(line)) {
                            line = line.replace("#projectName#", project.getBackendProject().getProjectName());
                            line = line.replace("#projectPort#", project.getBackendProject().getProjectPort());
                            writer.write(line);
                        }
                        writer.newLine();
                    }
                }
            }
        } catch (IOException e) {
            System.err.println("Failed to generate application.yml: " + e.getMessage());
        }
    }

    public static Map<String, String> genDatasourceConfig(Project project) {
        Map<String, String> datasourceConfigMap = new HashMap<>(2);
        String datasourceConfig = "";
        String mutiDatasourceConfig = "";
        ProjectDatasource projectDatasource = project.getProjectDatasource();

        String mutilDatasourceId = project.getMutilDatasourceId();
        List<ProjectDatasource> mutilDatasourceList = project.getMutilDatasourceList();
        if (StringUtils.isNotBlank(mutilDatasourceId) && CollectionUtil.isNotEmpty(mutilDatasourceList)) {
            // 定义文件路径
            String filePath = GenSb3Vue3Util.FILE_PATH_PRE + "resources\\config\\mutilDatasourceConfig";

            String mysqlDatabaseName = projectDatasource.getMysqlDatabaseName();
            mysqlDatabaseName = StrUtil.toCamelCase(mysqlDatabaseName);
            StringBuilder mutilDatasourceConfigStr = new StringBuilder();
            mutilDatasourceConfigStr.append("        "+mysqlDatabaseName+":\n");
            mutilDatasourceConfigStr.append("          url: "+ projectDatasource.getMysqlConnectUrl()+"\n");
            mutilDatasourceConfigStr.append("          username: "+ projectDatasource.getMysqlUsername()+"\n");
            mutilDatasourceConfigStr.append("          password: "+ projectDatasource.getMysqlPassword()+"\n");
            mutilDatasourceConfigStr.append("          driver-class-name: "+ projectDatasource.getMysqlDriver()+"\n");

            for (ProjectDatasource mutilDatasource : mutilDatasourceList) {
                String tempMysqlDatabaseName = mutilDatasource.getMysqlDatabaseName();
                tempMysqlDatabaseName = StrUtil.toCamelCase(tempMysqlDatabaseName);
                mutilDatasourceConfigStr.append("        "+tempMysqlDatabaseName+":\n");
                mutilDatasourceConfigStr.append("          url: "+ mutilDatasource.getMysqlConnectUrl()+"\n");
                mutilDatasourceConfigStr.append("          username: "+ mutilDatasource.getMysqlUsername()+"\n");
                mutilDatasourceConfigStr.append("          password: "+ mutilDatasource.getMysqlPassword()+"\n");
                mutilDatasourceConfigStr.append("          driver-class-name: "+ mutilDatasource.getMysqlDriver()+"\n");
            }

            // 使用 try-with-resources 自动管理 BufferedReader 的生命周期
            try (BufferedReader redisConfigBr = Files.newBufferedReader(Paths.get(filePath))) {
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = redisConfigBr.readLine()) != null) {
                    if (StringUtils.isNotBlank(line)) {
                        line = line.replace("#mysqlDatabaseName#", mysqlDatabaseName);
                        line = line.replace("#mutilDatasourceConfigStr#", mutilDatasourceConfigStr);
                        sb.append(line);
                    }
                    sb.append("\n");
                }
                mutiDatasourceConfig = sb.toString();
            } catch (IOException e) {
                // 处理可能发生的 IO 异常
                e.printStackTrace();
            }

        } else {
            // 定义文件路径
            String filePath = GenSb3Vue3Util.FILE_PATH_PRE + "resources\\config\\datasourceConfig";

            // 使用 try-with-resources 自动管理 BufferedReader 的生命周期
            try (BufferedReader redisConfigBr = Files.newBufferedReader(Paths.get(filePath))) {
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = redisConfigBr.readLine()) != null) {
                    if (StringUtils.isNotBlank(line)) {
                        line = line.replace("#MYSQL_CONNET_URL#", projectDatasource.getMysqlConnectUrl());
                        line = line.replace("#MYSQL_USERNAME#", projectDatasource.getMysqlUsername());
                        line = line.replace("#MYSQL_PASSWORD#", projectDatasource.getMysqlPassword());
                        line = line.replace("#MYSQL_DRIVER_CJ#", projectDatasource.getMysqlDriver());
                        sb.append(line);
                    }
                    sb.append("\n");
                }
                datasourceConfig = sb.toString();
            } catch (IOException e) {
                // 处理可能发生的 IO 异常
                e.printStackTrace();
            }
        }
        datasourceConfigMap.put("datasourceConfig", datasourceConfig);
        datasourceConfigMap.put("mutilDatasourceConfig", mutiDatasourceConfig);
        return datasourceConfigMap;
    }

    /**
     * 生成application-db.yml
     *
     * @param project
     */
    private void generationApplicationDBYml(Project project) {
        try {
            File classFile = GenUtil.newFile(project, "applicationConfig", "application-db");
            Map<String, String> genDatasourceConfig = genDatasourceConfig(project);
            String datasourceConfig = genDatasourceConfig.get("datasourceConfig");
            String mutiDatasourceConfig = genDatasourceConfig.get("mutilDatasourceConfig");
            // 使用 try-with-resources 保证资源自动关闭
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(classFile))) {
                File template = new File(FILE_PATH_PRE + "resources\\config\\application-db");
                try (BufferedReader br = new BufferedReader(new FileReader(template))) {
                    String line;
                    while ((line = br.readLine()) != null) {
                        if (StringUtils.isNotBlank(line)) {
                            line = line.replaceAll("#DATASOURCE_CONFIG#", datasourceConfig);
                            line = line.replaceAll("#MUTIL_DATASOURCE_CONFIG#", mutiDatasourceConfig);
                            if (StrUtil.isNotBlank(line)){
                                writer.write(line);
                                writer.newLine();
                            }
                        }

                    }
                }
            }
        } catch (IOException e) {
            // 更详细的错误信息
            System.err.println("Failed to generate application-db.yml: " + e.getMessage());
        }
    }
    /**
     * 生成application-swagger.yml
     *
     * @param project
     */
    private void generationApplicationSwaggerYml(Project project) {
        try {
            File classFile = GenUtil.newFile(project, "applicationConfig", "application-swagger");
            // 使用 try-with-resources 保证资源自动关闭
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(classFile))) {
                File template = new File(FILE_PATH_PRE + "resources\\config\\application-swagger");
                try (BufferedReader br = new BufferedReader(new FileReader(template))) {
                    String line;
                    while ((line = br.readLine()) != null) {
                        if (StringUtils.isNotBlank(line)) {
                            line = line.replaceAll("#GroupId#", project.getBackendProject().getProjectGroup());
                            writer.write(line);
                        }
                        writer.newLine();
                    }
                }
            }
        } catch (IOException e) {
            // 更详细的错误信息
            System.err.println("Failed to generate application-swagger.yml: " + e.getMessage());
        }
    }
    /**
     * 生成application-service.yml
     *
     * @param project
     */
    private void generationApplicationServiceYml(Project project) {
        try {
            File classFile = GenUtil.newFile(project, "applicationConfig", "application-service");
            // 使用 try-with-resources 保证资源自动关闭
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(classFile))) {
                File template = new File(FILE_PATH_PRE + "resources\\config\\application-service");
                String resourcesPre = Constants.ProjectDirSuffix.substring(0, Constants.ProjectDirSuffix.lastIndexOf("\\"));
                String uploadFilePath = project.getBackendProject().getProjectDir() + project.getBackendProject().getProjectName() + "\\" + resourcesPre + "\\resources\\sysUpload\\";
                String downloadTaskFilePath = project.getBackendProject().getProjectDir() + project.getBackendProject().getProjectName() + "\\" + resourcesPre + "\\resources\\sysDownload\\";

                try (BufferedReader br = new BufferedReader(new FileReader(template))) {
                    String line;
                    while ((line = br.readLine()) != null) {
                        if (StringUtils.isNotBlank(line)) {
                            line = line.replace("#projectName#", project.getBackendProject().getProjectName());
                            line = line.replace("#uploadfilePath#", uploadFilePath);
                            line = line.replace("#downloadTaskFilePath#", downloadTaskFilePath);
                            writer.write(line);
                        }
                        writer.newLine();
                    }
                }
            }
        } catch (IOException e) {
            // 更详细的错误信息
            System.err.println("Failed to generate application-service.yml: " + e.getMessage());
        }
    }

    /**
     * 生成application-security.yml
     *
     * @param project
     */
    private void generationApplicationSecurityYml(Project project) {
        try {
            File classFile = GenUtil.newFile(project, "applicationConfig", "application-security");
            // 使用 try-with-resources 保证资源自动关闭
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(classFile))) {
                File template = new File(FILE_PATH_PRE + "resources\\config\\application-security");
                try (BufferedReader br = new BufferedReader(new FileReader(template))) {
                    String line;
                    while ((line = br.readLine()) != null) {
                        if (StringUtils.isNotBlank(line)) {
                            writer.write(line);
                        }
                        writer.newLine();
                    }
                }
            }
        } catch (IOException e) {
            // 更详细的错误信息
            System.err.println("Failed to generate application-security.yml: " + e.getMessage());
        }
    }


    /**
     * 生成pom.xml
     *
     * @param project
     */
    private void generationPom(Project project) {
        try {
            File pomFile = GenUtil.newFile(project, "pom", "pom");

            // 使用 try-with-resources 保证资源自动关闭
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(pomFile))) {

                File template = new File(FILE_PATH_PRE + "pom");
                try (BufferedReader br = new BufferedReader(new FileReader(template))) {
                    String line;
                    while ((line = br.readLine()) != null) {
                        if (StringUtils.isNotBlank(line)) {
                            line = line.replaceAll("#GroupId#", project.getBackendProject().getProjectGroup());
                            line = line.replaceAll("#ArtifactId#", project.getBackendProject().getProjectName());
                            writer.write(line);
                        }
                        writer.newLine();
                    }
                }
            }
            //多数据源
            if (StrUtil.isNotBlank(project.getMutilDatasourceId())){
                GenSb3Vue3Addition.processDynamicDatasourceMaven(project);
            }
        } catch (IOException e) {
            // 更详细的错误信息
            System.err.println("Failed to generate pom.xml: " + e.getMessage());
        }
    }

}
